import axios from 'axios';

const API_BASE_URL = 'http://117.72.106.234:8080/api';

// ����axiosʵ��
const resourceApi = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// ���������� - ����token
resourceApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// ��Ӧ������ - ����token����
resourceApi.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      // token���ڣ�������ش洢����ת����¼ҳ
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export const resourceService = {
  // ��ȡ������Դ����
  getAllCategories: () => {
    return resourceApi.get(`${API_BASE_URL}/resource/category`);
  },

  // ��ȡ������������
  getCategoryById: (categoryId) => {
    return resourceApi.get(`${API_BASE_URL}/resource/category/${categoryId}`);
  },

  // �������ƻ�ȡ����
  getCategoryByName: (name) => {
    return resourceApi.get(`${API_BASE_URL}/resource/category/by-name`, { params: { name } });
  },

  // ȫ����Դ����
  searchGlobalResources: (searchParams) => {
    return resourceApi.post(`${API_BASE_URL}/resource/search/global`, searchParams);
  },

  // ��������Դ����
  searchNetworkResources: (searchParams) => {
    return resourceApi.post(`${API_BASE_URL}/resource/search/network`, searchParams);
  },

  // ��ȡ��Դ����
  getResourceDetail: (resourceId) => {
    return resourceApi.get(`${API_BASE_URL}/resource/search/detail/${resourceId}`);
  },

  // ������Դ
  createResource: (formData) => {
    return resourceApi.post(`${API_BASE_URL}/resource/create`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  // ������Դ
  updateResource: (resourceId, formData) => {
    return resourceApi.put(`${API_BASE_URL}/resource/update/${resourceId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  // ɾ����Դ
  deleteResource: (resourceId) => {
    return resourceApi.delete(`${API_BASE_URL}/resource/${resourceId}`);
  },

  // ��ȡ�û��ϴ�����Դ�б�
  getUserResources: (params) => {
    return resourceApi.get(`${API_BASE_URL}/resource/my-resources`, { params });
  },
};